package com.rsa.tools;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author lf
 * @Description: 获取公/私秘钥
 * @date 2020/7/30 12:31
 */
public class RsaTools {

    private static final Logger log = LoggerFactory.getLogger(RsaTools.class);

    /**
     * 获取私钥
     * @param privateKey 私钥字符串
     * @return  私钥
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        log.info("根据字符串转换成私钥....");
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     * @param publicKey 公钥字符串
     * @return  公钥
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        log.info("根据字符串转换成公钥....");
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }
}
